<?php
/**
 * Created by jinqiang on 2024/7/12 16:53.
 * Copyright (c) 2024, Your Company. All rights reserved.
 */


namespace App\Http\Services\Produce;


use App\Http\Models\Mysql\SsyJyProductCategoryTable;
use App\Http\Models\Mysql\SsyJyProductListTable;
use App\Http\Models\Mysql\SsyNewProductProcessSheetTable;
use App\Http\Models\Mysql\SsyNewProductsSizeTable;
use App\Http\Models\Mysql\SsyProcessingFactoryNameTable;
use App\Http\Models\Mysql\SsyProcessingListTable;
use App\Http\Models\Mysql\SsyProductlistBangdinTagTable;
use App\Http\Models\Mysql\StyleSizeTable;
use App\Http\Models\Mysql\StyleTable;
use App\Http\Repository\WmsRepository;
use Illuminate\Support\Facades\DB;

class TagService
{
    public function search($param)
    {
        $conn = new SsyProductlistBangdinTagTable();
        if($param['type_no'] ?? ""){
            $conn = $conn->where('type_no', 'like', $param['type_no']."%");
        }
        if($param['sku_code'] ?? ""){
            $conn = $conn->where('sku_code', 'like', $param['sku_code']."%");
        }
        $res = $conn->orderBy('createtime', 'desc')->paginate((Int)$param['limit'])->toArray();
        return [
            'data' => $res['data'],
            'total' => $res['total']
        ];
    }

    public function searchCheck($param)
    {
        $conn = DB::table("ssy_processing_list as p")->join("ssy_productlist_bangdin_tag as t", 'p.sku_code', '=', 't.sku_code')
            ->select(["p.id","p.processing_code", "p.sku_code", "p.factory_name", "p.type_no", "p.type_name", "p.order_processor", "p.num", "t.id as t_id",
                "t.safety_category", "t.executive_standard", "t.m_status", "t.push_jw_status", "t.product_name"]);
        if($param['processing_code'] ?? ""){
            $conn = $conn->where('p.processing_code', $param['processing_code']);
        }
        if($param['sku_code'] ?? ""){
            $conn = $conn->where('p.sku_code', 'like', $param['sku_code']."%");
        }
        if($param['factory_name'] ?? ""){
            $conn = $conn->where('p.factory_name', $param['factory_name']);
        }
        if(isset($param['m_status']) && $param['m_status'] != ""){
            $conn = $conn->where('t.m_status', $param['m_status']);
        }
        if(isset($param['push_jw_status']) && $param['push_jw_status'] != ""){
            $conn = $conn->where('t.push_jw_status', $param['push_jw_status']);
        }
        $res = $conn->orderBy('p.createtime', 'desc')->orderBy('p.id', 'asc')->paginate((Int)$param['limit'])->toArray();
        return [
            'data' => $res['data'],
            'total' => $res['total']
        ];
    }

    public function del($id)
    {
        return (new SsyProductlistBangdinTagTable())->deleteData($id);
    }

    public function getSku($typeNo)
    {
        $list = (new SsyJyProductListTable())->where('product_code', 'like', $typeNo."%")->get(['product_code as sku_code', 'product_name', 'a_parts'])->toArray();
        if(empty($list)){
            return [];
        }
        $skuCodeList = array_column($list, 'sku_code');
        //获取巨益的款名、数加的款名
        $styleObj = (new StyleTable())->where('number', $typeNo)->first(['short_name', 'name']);
        $productSheetObj = (new SsyNewProductProcessSheetTable())->where('type_no', $typeNo)->first(['executive_standard', 'safety_category']);
        return [
            'short_name' => $list[0]['a_parts'] ?: ($styleObj->short_name ?? ""),
            'executive_standard' => $productSheetObj->executive_standard ?? "",
            'safety_category' => $productSheetObj->safety_category ?? "",
            'sku_list' => $skuCodeList,
            'type_name' => $styleObj->name,
            'type_name_jy' =>$list[0]['product_name']
        ];
    }

    public function save($data)
    {
        $data = json_decode($data, true);
        $id = $data['id'] ?? "";
        $fabricList = ['lining_one', 'lining_two', 'lining_three', 'lining_four', 'lining_five'];
        $fabric = "";
        foreach ($fabricList as $column){
            if(empty($data[$column])){
                break;
            }
            $fabric .= $data[$column]."\r\n";
        }
        if(!empty($id)){
            $isBaseSize = strtoupper(substr($data['sku_code'], -1)) == "F";
            $saveData = [
                'type_no'=>trim($data['type_no']),
                'sku_code'=>$data['sku_code'],
                'safety_category'=>$data['safety_category'],
                'executive_standard'=>$data['executive_standard'],
                'product_name'=>$data['product_name'],
                'fabric'=> !$isBaseSize && !empty($fabric) ? $fabric . "(装饰部分除外)" : preg_replace("/\r\n$/is", "", $fabric),
                'lining_one'=>$data['lining_one'] ?? "",
                'lining_two'=>$data['lining_two'] ?? "",
                'lining_three'=>$data['lining_three'] ?? "",
                'lining_four'=>$data['lining_four'] ?? "",
                'lining_five'=>$data['lining_five'] ?? ""
            ];
            return (new SsyProductlistBangdinTagTable())->updateData($id, $saveData);
        }else{
            DB::beginTransaction();
            foreach($data['sku_code'] as $skuCode){
                $isBaseSize = strtoupper(substr($skuCode, -1)) == "F";
                $saveData = [
                    'type_no'=> trim($data['type_no']),
                    'sku_code'=>$skuCode,
                    'safety_category'=>$data['safety_category'],
                    'executive_standard'=>$data['executive_standard'],
                    'product_name'=>$data['product_name'],
                    'fabric' => !$isBaseSize && !empty($fabric) ? $fabric . "(装饰部分除外)" : preg_replace("/\r\n$/is", "", $fabric),
                    'lining_one'=>$data['lining_one'] ?? "",
                    'lining_two'=>$data['lining_two'] ?? "",
                    'lining_three'=>$data['lining_three'] ?? "",
                    'lining_four'=>$data['lining_four'] ?? "",
                    'lining_five'=>$data['lining_five'] ?? "",
                    'createtime'=>date("Y-m-d H:i:s")
                ];
                $res = (new SsyProductlistBangdinTagTable())->createData($saveData);
                if($res['code'] !== 0){
                    DB::rollBack();
                    return $res;
                }
            }
            DB::commit();
            return ['code' => 0, 'msg' => '创建成功'];
        }
    }

    //吊牌确认--预览
    public function preview($pId, $tId)
    {
        $tagObj = (new SsyProductlistBangdinTagTable())->where('id', (Int)$tId)->first()->toArray();
        $tagObj['show_tag_price'] = false;
        $tagObj['is_tz'] = false;
        //加工单
        $processingObj = (new SsyProcessingListTable())->where('id', (Int)$pId)->first()->toArray();
        //获取尺码表数据
        $sizeObj = (new SsyNewProductsSizeTable())->where('type_no', $tagObj['type_no'])->first(["plank_house_table_title","specifications_base_cdoe"]);
        $sizeObj = empty($sizeObj) ? ['plank_house_table_title' => [], 'specifications_base_cdoe' => []] : $sizeObj->toArray();
        //获取工艺信息 是否水洗 是否演出服
        $gyObj = (new SsyNewProductProcessSheetTable())->where('type_no', $tagObj['type_no'])->first(["is_perform","is_shuixi"]);
        $gyObj = empty($gyObj) ? ['is_perform' => 0, 'is_shuixi' => 0] : $gyObj->toArray();
        $tagObj['product_name'] .= $gyObj['is_perform'] ? "(演出服)" : ($gyObj['is_shuixi'] ? "(水洗产品)" : "");
        //获取款所对应的身高腰围
        if($sizeObj['plank_house_table_title']){
            if($sizeObj['specifications_base_cdoe']){
                $codeList = json_decode($sizeObj['specifications_base_cdoe'], true);
                foreach ($codeList['base_size_code'] as $item){
                    if($processingObj['size_code'] == $item['size_code']['title']){
                        if($tagObj['sku_code'] == "SYS183975M") {
                            $codeItem = [
                                "size_code" => ['id' => $item['size_code']['id'], "title" => ''],
                                "height_code" => ['id' => $item['height_code']['id'], "title" => ''],
                                "waist_code" => ['id' => $item['waist_code']['id'], "title" => '']
                            ];
                        }else if(in_array($tagObj['type_no'], ["YHF114898","YHF114899","YHF114868","YHF154651","YHF114969"])){
                            $codeItem = [
                                "size_code" => ['id'=>$item['size_code']['id'],"title"=>$processingObj['size_code']],
                                "height_code" => ['id'=>$item['height_code']['id'],"title"=>"160"],
                                "waist_code" => ['id'=>$item['waist_code']['id'],"title"=>'84']
                            ];
                        }else{
                            $codeItem = [
                                "size_code" => ['id'=>$item['size_code']['id'] ?? "","title"=>$processingObj['size_code']],//." 规格:(".$vv['specifications_base_cdoe'].")"
                                "height_code" => ['id'=>$item['height_code']['id'] ?? "","title"=>''],
                                "waist_code" => ['id'=>$item['waist_code']['id'] ?? "","title"=>'']
                            ];
                            $tagObj['specifications_base_cdoe']=" 规格:(".$item['specifications_base_cdoe'].")";
                        }
                        $tagObj['code_list'] = $codeItem;
                    }
                }
            }else{
                $codeList = json_decode($sizeObj['plank_house_table_title'], true);
                foreach ($codeList['code_list'] as $item) {
                    if($processingObj['size_code'] == $item['size_code']['title']){
                        if($tagObj['sku_code'] == "SYS183975M") {
                            $codeItem = [
                                "size_code" => ['id' => $item['size_code']['id'], "title" => ''],
                                "height_code" => ['id' => $item['height_code']['id'], "title" => ''],
                                "waist_code" => ['id' => $item['waist_code']['id'], "title" => '']
                            ];
                        }else if(in_array($tagObj['type_no'], ["YHF114898","YHF114899","YHF114868","YHF154651","YHF114969"])){
                            $codeItem = [
                                "size_code" => ['id'=>$item['size_code']['id'] ?? "","title"=>$processingObj['size_code']],
                                "height_code" => ['id'=>$item['height_code']['id'] ?? "","title"=>"160"],
                                "waist_code" => ['id'=>$item['waist_code']['id'] ?? "","title"=>'84']
                            ];
                        }else{
                            $codeItem = [
                                "size_code" => ['id'=>$item['size_code']['id'] ?? "","title"=>$processingObj['size_code']],
                                "height_code" => ['id'=>$item['height_code']['id'] ?? "","title"=>$item['height_code']['title'] ?? ""],
                                "waist_code" => ['id'=>$item['waist_code']['id'] ?? "","title"=>$item['waist_code']['title'] ?? ""]
                            ];
                        }
                        $tagObj['code_list'] = $codeItem;
                        $tagObj['specifications_base_cdoe'] = "";
                    }
                }
            }
        }else{
            $styleObj = (new StyleTable())->where('number', $tagObj['type_no'])->first();
            $styleSizeList = (new StyleSizeTable())->where('style_id', $styleObj->id)->get()->toArray();
            foreach ($styleSizeList as $item){
                preg_match_all("/(?:\()(.*)(?:\))/i",$item['size'], $result);
                $code = explode('/',$result[1][0] ?? "");
                if($processingObj['size_code'] == $item['size_number']){
                    if($tagObj['sku_code'] == "SYS183975M") {
                        $codeItem = [
                            "size_code" => ['id' => 1, "title" => ''],
                            "height_code" => ['id' => 1, "title" => ''],
                            "waist_code" => ['id' => 1, "title" => '']
                        ];
                    }else if(in_array($tagObj['type_no'], ["YHF114898","YHF114899","YHF114868","YHF154651","YHF114969"])){
                        $codeItem = [
                            "size_code" => ['id'=> 1,"title"=>$processingObj['size_code']],
                            "height_code" => ['id'=> 1,"title"=>"160"],
                            "waist_code" => ['id'=> 1,"title"=>'84']
                        ];
                    }else{
                        $codeItem = [
                            "size_code" => ['id'=> 1,"title"=>$processingObj['size_code']],
                            "height_code" => ['id'=> 1,"title"=> $code[0] ?? ""],
                            "waist_code" => ['id'=> 1,"title"=> $code[1] ?? ""]
                        ];
                    }
                    $tagObj['code_list'] = $codeItem;
                    $tagObj['specifications_base_cdoe'] = "";
                }
            }
        }
        //判断是否是童装
        if(str_starts_with($tagObj['type_no'], 'ST') ||  $tagObj['type_no']=='SGF152585'){
            $sizeCode = (Int)($tagObj['code_list']['size_code']['title'] ?? 0);
            $tagObj['fabric'] .= $sizeCode > 0 && $sizeCode <= 100 ? "\r\n(婴幼儿用品)" : "\r\n(本产品适合3岁以上儿童使用)";
            $tagObj['is_tz'] = true;
        }
        //获取公司地址
        $subjects = array_column(config("scm.subject"), "supplier_id", "brand_code_s");
        $supplierId = $subjects[$processingObj['brand_code']] ?? "";
        $factoryObj = (new SsyProcessingFactoryNameTable())->where('supplier_id', $supplierId)->first(["contact_address","company_tel","company_head"]);
        $tagObj['address'] = $factoryObj->contact_address ?? "";
        $tagObj['company_tel'] = $factoryObj->company_tel ?? "";
        $tagObj['company_head'] = $factoryObj->company_head ?? "";
        $tagObj['brand_name'] = $processingObj['brand_name'];
        if($tagObj['sku_code']=="SYS183975M"){
            $tagObj['address']="杭州市萧山区眉山路589号南岸11栋";
            $tagObj['company_head']='杭州快哉文化有限公司';
        }
        //吊牌价格
        $jyObj = (new SsyJyProductListTable())->where('product_code', $tagObj['sku_code'])->first(['tag_price']);
        $tagObj['tag_price'] = $jyObj->tag_price ?? 0;
        $tagObj['show_tag_price'] = !empty($tagObj['tag_price']) ? true : false;
        //加工单对应的工厂吊牌编号
        $factoryTagNumberObj = (new SsyProcessingFactoryNameTable())->where('supplier_id', $processingObj['supplier_id'])->first();
        $tagObj['tag_number'] = $factoryTagNumberObj->tag_number ?? "";
        return $tagObj;
    }

    public function checkStatus($ids, $status)
    {
        $ids = json_decode($ids, true);
        $status = (Int)$status;
        $tIds = array_column($ids, 't_id');
        if($status === 0){
            //取消确认状态，同时修改推送状态
            return (new SsyProductlistBangdinTagTable())->updateData($tIds, ['m_status' => $status, 'push_jw_status' => 0, 'confirm_time' => date("Y-m-d H:i:s")]);
        }
        $this->push($ids);
        return (new SsyProductlistBangdinTagTable())->updateData($tIds, ['m_status' => $status, 'confirm_time' => date("Y-m-d H:i:s")]);
    }

    public function push($data)
    {
        foreach($data as $item){
            list($pId, $tId) = [(Int)$item['p_id'], (Int)$item['t_id']];
            $tagObj = (new SsyProductlistBangdinTagTable())->where('id', $tId)->first()->toArray();
            $processingObj = (new SsyProcessingListTable())->where('id', $pId)->first(['size_code', 'brand_code'])->toArray();
            //巨益商品信息
            $jyObj = (new SsyJyProductListTable())->where('product_code', $tagObj['sku_code'])->first();
            $jyObj = !empty($jyObj) ? $jyObj->toArray() : [];
            //获取款所对应的身高腰围
            $sizeObj = (new SsyNewProductsSizeTable())->where('type_no', $tagObj['type_no'])->first();
            $sizeObj = !empty($sizeObj) ? $sizeObj->toArray() : [];
            $heightWaist = "";
            if($sizeObj['plank_house_table_title'] ?? []){
                $plankHouseTableTitle = json_decode($sizeObj['plank_house_table_title'], true);
                foreach($plankHouseTableTitle['code_list'] as $codeListItem){
                    if($processingObj['size_code'] == $codeListItem['size_code']['title']){
                        $heightWaist = $codeListItem['height_code']['title']??"" && $codeListItem['waist_code']['title']??"" ?
                                $codeListItem['height_code']['title']."/".$codeListItem['waist_code']['title'] : "";
                    }
                }
            }else{
                $styleObj = (new StyleTable())->where('number', $tagObj['type_no'])->first();
                $styleSizeList = (new StyleSizeTable())->where('style_id', $styleObj->id)->get()->toArray();
                foreach ($styleSizeList as $styleSizeItem) {
                    preg_match_all("/(?:\()(.*)(?:\))/i", $styleSizeItem['size'], $result);
                    $code = explode('/', $result[1][0] ?? "");
                    if($processingObj['size_code'] == $styleSizeItem['size_number']){
                        $heightWaist = $code[0]??"" && $code[1]??"" ? $code[0]."/".$code[1] : "";
                    }
                }
            }
            //判断是否是童装
            $fabric = "";
            if(strpos($tagObj['type_no'],'ST') !== false ||  $tagObj['type_no']=='SGF152585'){
                $fabric = "(本产品适合3岁以上儿童使用)";
            }
            //获取分类
            $jyCategoryObj = (new SsyJyProductCategoryTable())->where('category_name', $jyObj['commodity_classification'] ?? "")->first();
            $jyCategoryObj = !empty($jyCategoryObj) ? $jyCategoryObj->toArray() : [];
            //货主信息
            $subjects = array_column(config("scm.subject"), "owner_code", "brand_code_s");
            $goodsOwner = $subjects[$processingObj['brand_code']];
            //获取可撕标
            $gyObj = (new SsyNewProductProcessSheetTable())->where('type_no', $tagObj['type_no'])->first(['tearable_label_img']);
            $gwf11 = isset($gyObj->tearable_label_img) && !empty($gyObj->tearable_label_img) ? "手撕标" : "";
            $pushData['items'] = [
                [
                    "goodsOwner" => $goodsOwner,
                    "brandCode" => $jyObj['brand_code'] ?? "",
                    "brandName" => $jyObj['brand_name'] ?? "",
                    "categoryCode" => $jyCategoryObj['category_code'] ?? "",
                    "categoryName" => $jyObj['commodity_classification'] ?? "",
                    "goodsType" => "P",
                    "sku" => $tagObj['sku_code'],
                    "gwf1" => $tagObj['safety_category'],
                    "gwf2" => $tagObj['executive_standard'],
                    "gwf9" => $fabric,
                    "gwf10" => $tagObj['product_name'],
                    "gwf11" => $gwf11,
                    "url" => $jyObj['img'] ?? "",
                    "url1" => $jyObj['img'] ?? "",
                    "inst" => $heightWaist
                ]
            ];
            $liningList = ['lining_one', 'lining_two', 'lining_three', 'lining_four', 'lining_five'];
            foreach ($liningList as $index => $column){
                if(empty($tagObj[$column])){
                    break;
                }
                $pushData['items'][0]['gwf'.($index+3)] = $tagObj[$column];
                $pushData['items'][0]['gwf'.($index+4)] = "(装饰部分除外)";
            }
            $res = WmsRepository::pushTag($pushData);
            if($res['success']){
                (new SsyProductlistBangdinTagTable())->updateData($tId, ['push_jw_status' => 1]);
            }else{
                info("吊牌推送失败", [$pushData, $res]);
                return ['code' => -1, 'msg' => $res['body'], 'data' => $res];
            }
        }
        return ['code' => 0, 'msg' => '推送成功'];
    }
}
